package com.hkccommunity.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseController extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        自定义控制器
//        全局设置请求为utf-8
        req.setCharacterEncoding("utf-8");
        String uri = req.getRequestURI();
        int indexOf = uri.lastIndexOf("/");
        String methodName = uri.substring(indexOf + 1);
        //获取字节码文件
        Class<? extends BaseController> cls = this.getClass();
        try {
            //创建实例化对象
            Method method = cls.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}
